// math utilities
import {getArea} from 'ol/sphere';
import {getIntersection}  from 'ol/extent';
import {Style,Icon} from 'ol/style';


// coordinates; will return the length of the [a, b] segment
function length(a, b) {
    return Math.sqrt(
      (b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1])
    );
  }
  
  // coordinates; will return true if c is on the [a, b] segment
  function isOnSegment(c, a, b) {
    const lengthAc = length(a, c);
    const lengthAb = length(a, b);
    const dot =
      ((c[0] - a[0]) * (b[0] - a[0]) + (c[1] - a[1]) * (b[1] - a[1])) / lengthAb;
    return Math.abs(lengthAc - dot) < 1e-6 && lengthAc < lengthAb;
  }
  
  // modulo for negative values, eg: mod(-1, 4) returns 3
  function mod(a, b) {
    return ((a % b) + b) % b;
  }
  
  // returns a coordinates array which contains the segments of the feature's
  // outer ring between the start and end points
  // Note: this assumes the base feature is a single polygon
  function getPartialRingCoords(feature, startPoint, endPoint) {
    let polygon = feature.getGeometry();
    if (polygon.getType() === 'MultiPolygon') {
      polygon = polygon.getPolygon(0);
    }
    const ringCoords = polygon.getLinearRing().getCoordinates();
  
    let i,
      pointA,
      pointB,
      startSegmentIndex = -1;
    for (i = 0; i < ringCoords.length; i++) {
      pointA = ringCoords[i];
      pointB = ringCoords[mod(i + 1, ringCoords.length)];
  
      // check if this is the start segment dot product
      if (isOnSegment(startPoint, pointA, pointB)) {
        startSegmentIndex = i;
        break;
      }
    }
  
    const cwCoordinates = [];
    let cwLength = 0;
    const ccwCoordinates = [];
    let ccwLength = 0;
  
    // build clockwise coordinates
    for (i = 0; i < ringCoords.length; i++) {
      pointA =
        i === 0
          ? startPoint
          : ringCoords[mod(i + startSegmentIndex, ringCoords.length)];
      pointB = ringCoords[mod(i + startSegmentIndex + 1, ringCoords.length)];
      cwCoordinates.push(pointA);
  
      if (isOnSegment(endPoint, pointA, pointB)) {
        cwCoordinates.push(endPoint);
        cwLength += length(pointA, endPoint);
        break;
      } else {
        cwLength += length(pointA, pointB);
      }
    }
  
    // build counter-clockwise coordinates
    for (i = 0; i < ringCoords.length; i++) {
      pointA = ringCoords[mod(startSegmentIndex - i, ringCoords.length)];
      pointB =
        i === 0
          ? startPoint
          : ringCoords[mod(startSegmentIndex - i + 1, ringCoords.length)];
      ccwCoordinates.push(pointB);
  
      if (isOnSegment(endPoint, pointA, pointB)) {
        ccwCoordinates.push(endPoint);
        ccwLength += length(endPoint, pointB);
        break;
      } else {
        ccwLength += length(pointA, pointB);
      }
    }
  
    // keep the shortest path
    return ccwLength < cwLength ? ccwCoordinates : cwCoordinates;
  }


  
const formatArea = function(polygon) {
  
	var area;
	area = Math.abs(getArea(polygon,{projection:'EPSG:4326'}));
	var m2 = (Math.round(area * 100) / 100);
	var mu = m2*0.0015;
	mu = CurrencyFormatted(mu);
	return mu;
};
	
/**
 * 四舍五入
 */
function CurrencyFormatted(amount) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	 i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	var s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}


/**
	 * 输出RGB格式染色(0,0,0)
	 * @returns {String}
	 */
 function colorRgb (s){
  const   reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  var sColor = s.toLowerCase();
   if(sColor && reg.test(sColor)){
     if(sColor.length === 4){
       var sColorNew = "#";
       for(var i=1; i<4; i+=1){
         sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));
       }
       sColor = sColorNew;
     }
     //处理六位的颜色值
     var sColorChange = [];
     for( i=1; i<7; i+=2){
       sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));
     }
     return "" + sColorChange.join(",");
   }else{
     return sColor;
   }
 }


 /**
     * 判断地块是否在(基地或分区)范围内
     */
 function tunnelInfoInPolygon(feature,targetSource,inset){
    var returnFeature;
    var features = targetSource.getFeatures();
    var coordinates = feature.getGeometry().getCoordinates();

      if(feature.getGeometry().getType() == "Point"){
          var latlng = coordinates;
          for(var x = 0,y = features.length ;x < y; x++){// 判断第一个点是否在某个对象中
              var feature_temp = features[x];
              var isIn = feature_temp.getGeometry().intersectsCoordinate(coordinates);
              if(isIn){
                  returnFeature = feature_temp;
                  break;
              }else if(x == y-1){
                  return null;
              }
          }
      }else if(feature.getGeometry().getType() == "Polygon"){
        
        var extent1 = feature.getGeometry().getExtent();
        
          latlng = coordinates[0][0];
          for( x = 0,y = features.length ;x < y; x++){// 判断第一个点是否在某个对象中
                feature_temp = features[x];
              
              if(inset){
                var extent2 = feature_temp.getGeometry().getExtent();
                var obj = getIntersection(extent1,extent2) ;
                if( obj[0] != Infinity){
                  return feature_temp;
                }
              }
              
                isIn = feature_temp.getGeometry().intersectsCoordinate(latlng);
              if(isIn){
                  returnFeature = feature_temp;
                  if(inset) return feature_temp;
                  break;
              }else if(x == y-1){
                  return null;
              }
          }
          for(var i = 1,j = coordinates[0].length ; i < j; i++){//判断其余的坐标点是否都在同一个polygon
                latlng = coordinates[0][i];
              if(typeof(returnFeature) == 'undefined') continue;
                isIn = returnFeature.getGeometry().intersectsCoordinate(latlng);
              if(!isIn){
                  return null;
              }
          }
      }
    return returnFeature;
  }

  function getCoordinateGroup(coor){
    try{
      var coordinateGroup = JSON.parse(coor);
      return  coordinateGroup;
    }catch(e){
      return null;
    } 
  }

  var imgStyleCache = {};
  function  createImgStyle(isrc,scale=1){
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var image1 = new Image();
    image1.src = isrc;
    image1.onload = function () {
        ctx.save();
        ctx.beginPath();
        ctx.arc(30, 30,30, 0, 2 * Math.PI);//x,y,r
        ctx.closePath();
        ctx.strokeStyle = "#dfe43e";
        ctx.lineWidth = 1;
        ctx.clip();
        ctx.drawImage(image1,0,0,60,60);
        ctx.stroke();
        ctx.restore();
    }
    var style = imgStyleCache[isrc];
    if (!style) {
        style = new Style({
            image: new Icon( ({
                anchor: [0.5, 33],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                rotateWithView : true,
                img: canvas,
                imgSize: [60,60],
                scale: scale
            })),
            zIndex : 4
        });
        imgStyleCache[isrc] = style;
    }
    return style;
}

export {formatArea,colorRgb,tunnelInfoInPolygon,getCoordinateGroup,createImgStyle}
	